package com.blog.personalblog.controller;

import com.blog.personalblog.config.page.PageRequest;
import com.blog.personalblog.config.page.PageResult;
import com.blog.personalblog.entity.Category;
import com.blog.personalblog.entity.Tag;
import com.blog.personalblog.service.CategoryService;
import com.blog.personalblog.service.TagService;
import com.blog.personalblog.util.JsonResult;
import com.blog.personalblog.util.PageUtil;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Api(tags = "标签管理")
@RestController
@RequestMapping("/tag")
public class TagController {
    @Autowired
    TagService tagService;

    @ApiOperation(value = "标签列表")
    @PostMapping("/list")
    public JsonResult<Object> listPage(@RequestBody @Valid PageRequest pageRequest){
        List<Tag> tagList = tagService.getTagPage(pageRequest);
        PageInfo pageInfo = new PageInfo(tagList);
        PageResult pageResult = PageUtil.getPageResult(pageRequest,pageInfo);
        return JsonResult.success(pageResult);
    }
    @ApiOperation(value = "添加标签")
    @PostMapping("/create")
    public JsonResult<Object> tagCreate(@RequestBody @Valid Tag tag){
        int isStatus = tagService.createTag(tag);
        if (isStatus == 0){
            return  JsonResult.error("添加标签失败");
        }
        return JsonResult.success();
    }
    @ApiOperation(value = "修改标签" )
    @PostMapping("/update")
    public JsonResult<Object> tagUpdate(@RequestBody @Valid Tag tag){
        int isStatus = tagService.updateTag(tag);
        if(isStatus == 0){
            return  JsonResult.error("修改标签失败");
        }
        return JsonResult.success();
    }
    @ApiOperation(value = "删除标签")
    @PostMapping("/delete/{id}")
    public JsonResult<Object> categoryDelete(@PathVariable(value = "id") Integer id){
        tagService.deleteTag(id);
        return JsonResult.success();
    }
    @ApiOperation(value = "按编码查询标签")
    @PostMapping("/query/{id}")
    public JsonResult<Object> tagById(@PathVariable(value = "id") Integer id){
        Tag tag = tagService.getTagById(id);
        if (null == tag){
            return JsonResult.error("未查询到数据。");
        }
        return JsonResult.success(tag);
    }
    @ApiOperation(value = "批量添加标签")
    @PostMapping("/batchCreate")
    public JsonResult<Object> batchCreateTag(@RequestBody @Valid Tag tags){
        try{
            boolean isStatus = tagService.batchAddTag(tags.getTagName());
        }catch (Exception e){
            return JsonResult.error(e.getMessage());
        }
        return JsonResult.success();
    }
}
